package com.ruoyi.business.shop.service.impl;


import com.ruoyi.business.shop.constants.QCRconstants;
import com.ruoyi.business.shop.constants.ShopConstant;
import com.ruoyi.business.shop.api.domain.Shop;


import com.ruoyi.business.shop.api.domain.ShopVerification;
import com.ruoyi.business.shop.domain.vo.LoginShop;
import com.ruoyi.business.shop.domain.vo.ShopRegister;
import com.ruoyi.business.shop.exception.ShopException;
import com.ruoyi.business.shop.mapper.ShopMapper;
import com.ruoyi.business.shop.service.ShopLoginService;

import com.ruoyi.business.shop.utils.SMSSendUtils;

import com.ruoyi.business.shop.mapper.ShopVerificationMapper;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.CaptchaException;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.security.SecureRandom;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import com.ruoyi.business.shop.utils.OCRUtils;

/**
 * @ClassName: ShopLoginServiceImpl
 * @description: $
 * @author: GCC
 * @date: 2025/2/21 17:37
 * @Version: 1.0
 */

@Service
public class ShopLoginServiceImpl implements ShopLoginService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private ShopVerificationMapper shopVerificationMapper;

    @Autowired
    private RemoteUserService remoteUserService;


    @Resource
    private RedisTemplate redisTemplate;


    @Override
    public Map login(String code, String mobile ) {


        System.out.println("登录接收到手机号"+mobile);

        //获取登录数据

        if (StringUtils.isEmpty(code))
        {
            throw new CaptchaException("验证码不能为空");
        }
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + mobile;
        String captcha = redisService.getCacheObject(verifyKey);
        System.out.println("loging------");
        System.out.println("key:"+verifyKey);
        System.out.println("code:"+code);
        System.out.println("获取验证码存储"+captcha);
        System.out.println("---------loging");
        if (captcha == null)
        {
            throw new CaptchaException("验证码已失效");
        }
//            redisService.deleteObject(verifyKey);
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException("验证码错误");
        }


        //验证成功  清除缓存  查询验证表 通过手机号 获得商家信息
        //清除缓存
        redisService.deleteObject(verifyKey);

        //验证码校验结束

        Shop shop = new Shop();
        ShopVerification shopVerification = new ShopVerification();
        shopVerification.setMobile(mobile);
        shop.setShopVerification(shopVerification);

        List<Shop> shops = shopMapper.selectShopList(shop);


        if (Objects.isNull(shops) || shops.size()==0){
            throw new ShopException("手机号未注册");
        }
        //通过手机号 查询商铺信息

        shop=shops.get(0);
        if (shop.getAuditStatusId() == ShopConstant.DEFAULT )
        {
            throw new ShopException("待审核中。请等待");
        }

        if (shop.getAuditStatusId() == ShopConstant.SYS_PASS )
        {
            throw new ShopException("待人工审核中。请等待");
        }

        if (shop.getAuditStatusId() == ShopConstant.FAIL)
        {
            throw new ShopException("注册失败,重新注册");
        }

        //剩余已审核通过的




        //比较 手机号验证码

//        //对比redis数据
//        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + loginShop.getMobile();
//
//        redisService.setCacheObject(verifyKey,code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);



        //






//        System.out.println("shops = " + shops);

//        ShopVerification shopVerification = shopVerificationMapper.selectShopByMobile(mobile);


        //商铺手机号 关联查询 系统用户表  So 商铺信息表 要关联 系统用户id

        //获得系统用户对象

        //获得用户权限

        String username=shop.getName();
        //生成loginUser
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);


        //获取权限
        LoginShop loginShop = new LoginShop();
        loginShop.setSysUser(userResult.getData().getSysUser());
        loginShop.setRoles(userResult.getData().getRoles());
        loginShop.setPermissions(userResult.getData().getPermissions());
        System.out.println("userResult.getData() = " + userResult.getData());
        //补充商铺信息

        loginShop.setShop(shop);

        //生成token

//
//
        Map<String, Object> token = tokenService.createToken(loginShop);

        token.put("shop",shop);


        return token;
    }

    @Override
    @Transactional
    public String register(ShopRegister shopRegister) {



        System.out.println("shopRegister = " + shopRegister);





        String msg=null;
        Shop shop = new Shop();
        // 注册店铺
        shop.setName(shopRegister.getName());
        //经营区域
        shop.setOperatingArea(shopRegister.getOperatingArea());

//        shop.setRegTime(new Date());

        shop.setStartTime(shopRegister.getStartTime());
        shop.setEndTime(shopRegister.getEndTime());

        shop.setAddress(shopRegister.getAddress());
        shop.setLongitude(shopRegister.getLongitude());
        shop.setLatitude(shopRegister.getLatitude());
        shop.setDescription(shopRegister.getDescription());
        shop.setPhoto(shopRegister.getPhoto());

        //所属区域 地址转 ip   得到市
        shop.setArea(shopRegister.getArea());
        //  店铺表 添加数据

        //
        System.out.println("注册商品表" + shop);
        ShopVerification shopVerification = new ShopVerification();

        //认证表添加数据

        shopVerification.setDirector(shopRegister.getDirector());
        shopVerification.setIdCard(shopRegister.getIdCard());
        //添加手机号
        shopVerification.setMobile(shopRegister.getMobile());
        shopVerification.setBusinessLicenseId(shopRegister.getBusinessLicenseId());

        shopVerification.setBusinessLicenseImg(shopRegister.getBusinessLicenseImg());
        shopVerification.setFront(shopRegister.getFront());
        shopVerification.setOpposite(shopRegister.getOpposite());

        shop.setShopVerification(shopVerification);

        System.out.println("shop = " + shop);
        //检测已注册   验证表里 是否有 改手机号记录
        List<Shop> shops = shopMapper.selectShopList(shop);



        System.out.println("shops = " + shops);

        shops.forEach(System.out::println);
        if (shops.size() !=0 ){
            shops.forEach(System.out::println);
            throw new ShopException("该手机号已注册");
        }

        System.out.println("未注册");

        //未注册 视为新用户进行注册






        //执行机器审核

        System.out.println("--------机器审核");

        if (!recognizeid(shopRegister)){

            throw new ShopException("证件识别不一致");
        };



        shopMapper.insertShop(shop);

        shopVerification.setMid(shop.getId());

        System.out.println("注册认证表数据" + shopVerification);
        shopVerificationMapper.insertShopVerification(shopVerification);







         //审核通过


        shop.setAuditStatusId(ShopConstant.SYS_PASS);

        shopMapper.updateShop(shop);

        //机器审核通过后 等待 人工审核

            msg="等待人工审核";

        return msg;
    }

    @Override
    public String getLoginCode(String mobile) {

        String msg=null;
        //获取登录验证码
        msg="手机号错误";
        //检索认证表是否存在 商铺信息  手机号未注册||

        msg="手机号未注册";

        //检索认证表存在  检索是否审核通过  审核未通过

        msg="审核未通过";
        //通过  发送验证码 同时存储到缓存之中

        String code = getCode(mobile);

        SMSSendUtils.sendMessage(mobile,code);

        return msg;
    }

    @Override
    public String getCode(String mobile) {

        String msg=null;
        //调用阿里云发送验证码
        String code = createCode();

            SMSSendUtils.sendMessage(mobile,code);


        //并存储到 redis中
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + mobile;
        redisService.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        Object cacheObject = redisService.getCacheObject(verifyKey);
        System.out.println("------");
        System.out.println("key:"+verifyKey);
        System.out.println("code:"+code);
        System.out.println("获取验证码存储"+cacheObject);
        System.out.println("------gggggg");
        return msg;
    }

   private  String createCode(){
        String code;
        // 生成验证码
        SecureRandom secureRandom = new SecureRandom();
        StringBuilder captchaBuilder = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            int digit = secureRandom.nextInt(10);
            captchaBuilder.append(digit);
        }
        code=captchaBuilder.toString();
        return code;
    }

    @Override
    public int pass(Long id) {
        //获取 商铺信息

        System.out.println("审核通过 店铺id"+id);

        Shop shop = shopMapper.selectShopById(id);


        //系统注册商铺信息
         registerShop(shop);

        //商铺状态改为 通过审核

        shop.setAuditStatusId(ShopConstant.PASS);

        shopMapper.updateShop(shop);

        //2. 店铺放至 redis中

        /*
        *   key value
            shop_id:店铺id 店铺信息
            shops 经度 纬度 店铺id
        * */

        setShopRedis(shop);


//        return registerResult.getCode();

        return 200;
    }

    private  void   registerShop(Shop shop){

        //审核通过之后，1. 向系统用户表插入一条数据，并且分配商家角色
        String name = shop.getName(); //系统用户名 用店名
        // 注册用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserName(name);
        sysUser.setNickName(name);

        sysUser.setRoleIds(new Long[]{ShopConstant.SHOPROLEID});
        String password ="123456";

        sysUser.setPassword(SecurityUtils.encryptPassword(password));

        //远程调用注册用户信息

        R<SysUser> sysUserResult = remoteUserService.registerShop(sysUser);

        //系统用户表插入的数据
        SysUser data = sysUserResult.getData();

        System.out.println("data = " + data);


//        recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功");

        System.out.println("注册结果"+data);





    }

    private  void setShopRedis(Shop shop){

        //存储商铺 redis
        redisService.setCacheObject(ShopConstant.SHOP_KEY+shop.getId(),shop);
        //存储商铺地理位置redis
        redisService.setGeo(ShopConstant.SHOP_GEO, Double.parseDouble(shop.getLongitude()) ,Double.parseDouble(shop.getLatitude()),shop.getId());


        //获取数据

        List<Point> nearby = redisTemplate.opsForGeo().position(ShopConstant.SHOP_GEO, shop.getId());

    }


    private  boolean recognizeid(ShopRegister shopRegister ){

        //识别    营业执照

        try {
            Map<String, String> map = OCRUtils.recognizeidBusinessLicense(shopRegister.getBusinessLicenseImg());

            //负责人/营业执照号码 和 营业执照图片
            if (!map.get(QCRconstants.LEGAL_PERSON).equals(shopRegister.getDirector())){

                return false;
            }
            if (!map.get(QCRconstants.CREDIT_CODE).equals(shopRegister.getBusinessLicenseId())){

                return false;
            }


        } catch (Exception e) {
            throw new ShopException("营业执照识别异常");
        }
        System.out.println("营业执照验证成功");

        //识别    身份证

        try {
            Map<String, String> map = OCRUtils.recognizeidCard(shopRegister.getFront());

            //负责人/身份证号
//            if (!map.get(QCRconstants.NAME).equals(shopRegister.getDirector())){
//
//                return false;
//            }
            if (!map.get(QCRconstants.ID_NUMBER).equals(shopRegister.getIdCard())){
                System.out.println("身份证验证失败 ");
                return false;
            }


        } catch (Exception e) {
            throw new ShopException("身份证识别异常");
        }
        System.out.println("身份证验证成功");

        return true;



    }





}
